﻿using Newtonsoft.Json;
using Qiniu.Http;
using Qiniu.Util;
using QiNiu.Model.Response.rtc;
using System;
using System.Collections.Generic;
using System.Text;

namespace QiNiu.RTC
{
   public class RTCManager
    {

       
        
        public const string _apiDomain = "http://rtc.qiniuapi.com/v3/";

        private Mac mac;

        private Auth auth;

        public RTCManager(Mac mac) 
        {
            this.mac = mac;
            this.auth = new Auth(mac);
        }
        /// <summary>
        /// RoomToken 签发服务
        /// </summary>
        /// <param name="appId">应用编号</param>
        /// <param name="roomName">房间名称（同一APP下房间名称一致视为一个房间^[a-zA-Z0-9_-]{3,64}$）</param>
        /// <param name="userId">自定义用户编号^[a-zA-Z0-9_-]{3,50}$</param>
        /// <param name="expireAt">int64 类型，鉴权的有效时间，传入以秒为单位的 64 位 Unix 绝对时间，token 将在该时间后失效</param>
        /// <param name="permission"></param>
        /// <returns></returns>
        public string CreateRoomToken(string appId, string roomName, string userId, long? expireAt, string permission)
        {

            if (expireAt == null) 
            {
                expireAt= UnixTimestamp.GetUnixTimestamp(60*2);
            }

            return auth.CreateRoomToken(appId,roomName,userId, expireAt.Value,permission);
                     
        }

        /// <summary>
        /// 列出指定房间下当前所有用户
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="roomName"></param>
        /// <returns></returns>
        public RTCGetUsersResponse GetUsers(string appId,string roomName) 
        {

            var result = new RTCGetUsersResponse();

            var url = _apiDomain+ $"apps/{appId}/rooms/{roomName}/users";

            var token = auth.CreateRtcToken(url,"","","GET");

            var r = new HttpManager().Get(url,token);

            result.Code = r.Code;

            result.Text = r.Text;

            result.RefText = r.RefText;

            if (r.Code == 200) 
            {
                result.users = JsonConvert.DeserializeObject<List<RTCGetUsersResponseUser>>(r.Text);

            }

            return result;

        }




    }
}
